package com.guo.mixframe.framework.receivers.rpc

import com.guo.mixframe.framework.annotations.RpcController
import com.guo.mixframe.framework.configs.CoreConfig
import com.guo.mixframe.framework.log.LogPrint
import com.guo.mixframe.framework.urls.URLMapping
import com.guo.mixframe.framework.utils.PackageUtils
import com.guo.mixframe.launcher.Main
import io.vertx.core.DeploymentOptions
import io.vertx.core.Vertx

/**
 * @author  gx
 * @description
 */
object RpcService {

  fun deployRpcReceiver(vertx: Vertx) {
    val d = DeploymentOptions()
    d.instances = vertx.nettyEventLoopGroup().count()/2
    vertx.deployVerticle(RpcReceiver::class.java, d)
    LogPrint.logger.debug("Deploy receiver: ${RpcReceiver::class.qualifiedName}")
  }

  fun deployRpcDispatcher(vertx: Vertx) {
    val coreConfig = CoreConfig.getInstance()
    val controllerUrls = getRpcUrls()
    controllerUrls.entries
      .asSequence()
      .filter { coreConfig.isUrlTypeValid(it.key) }
      .forEach {
        //每种rpc类型部署一个分派器
        val options = DeploymentOptions()
        options.isWorker = true
        val dispatcher = RpcDispatcher()
        dispatcher.urls = it.value
        vertx.deployVerticle(dispatcher,options)
        LogPrint.logger.debug("Debug dispatcher:${dispatcher::class.qualifiedName}")
      }
  }

  private fun getRpcUrls(): Map<Int,Set<String>> {
    val annotationClass = RpcController::class
    val controllerUrls = mutableMapOf<Int,MutableSet<String>>()
    val klasses = PackageUtils.getClassesByAnnotation("com.gx.mixframe",annotationClass)
    for(klass in klasses){
      val className = klass.qualifiedName?:continue
      val urls = URLMapping.getUrls(className)
      if(urls.isEmpty()){
        continue
      }
      val annotation = klass.annotations.firstOrNull{it.annotationClass == annotationClass}?:continue
      val urlType = (annotation as RpcController).urlType
      val urlsByType = controllerUrls.computeIfAbsent(urlType){ mutableSetOf<String>() }
      urlsByType.addAll(urls)
    }
    return controllerUrls
  }


}
